#include "../include/Utils.hpp"
#include <cmath>
using namespace klas;

Real Utils::m_fpsFrame = 0;
Real Utils::m_fps = 0;
Timer Utils::m_fpsTimer;
ofstream Utils::m_file;

bool Utils::isEqual(Real a, Real b)
{
	if(fabs(a-b) < 1E-12)
		return true;

	return false;
}

Real Utils::getFPS()
{
	++m_fpsFrame;
	if(m_fpsTimer.getMilliseconds() > 150)
	{
		m_fpsTimer.restart();
		if(m_fpsTimer.getSeconds() != 0)
			m_fps = m_fpsFrame / m_fpsTimer.getSeconds();
		else
			m_fps = m_fpsFrame;
		m_fpsFrame = 0;
	}
	
	return m_fps;
}

Real Utils::random(Real min, Real max)
{
  if(min < 1000.0 || max < 1000.0)
  {
    // how accurate the decmial should be
    Real accuracy = 10000;
    if (min>max)
      return ((max * accuracy) + Real(((min * accuracy)-(max * accuracy)+1)*rand()/(RAND_MAX+1.0))) / accuracy;

    return ((min * accuracy)+Real(((max * accuracy)-(min * accuracy)+1)*rand()/(RAND_MAX+1.0))) / accuracy;
  }

  if (min>max)
    return max+Real((min-max+1)*rand()/(RAND_MAX+1.0));

  return min+Real((max-min+1)*rand()/(RAND_MAX+1.0));
}

bool Utils::log(string obj)
{
  m_file << obj << endl;
  m_file.flush();
  return !m_file.bad();
}

bool Utils::init(string logPath)
{
  m_file.open(logPath.c_str(), ios::out | ios::app); // Open the file in output mode and start at the end of the fil
  // if we failed to open the file, then return false
  if(!m_file.is_open())
          return false;
  // create a new section
  return log("\n\n\n---------------------------------------------");
}
